package com.example.demo.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.demo.R;
import com.example.demo.entity.Goods;
import com.example.demo.entity.Message;

import java.util.ArrayList;
import java.util.List;

public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatHolder> {
    public ChatAdapter() {
    }

    private List<Message> messages = new ArrayList<>();

    public void setData(List<Message> messages){
        this.messages = messages;
        notifyDataSetChanged();
    }

    public void setMessage(Message message){
        if (messages.size() % 2 ==0){
            message.setType(Message.MINE);
        }
        else {
            message.setType(Message.OTHER);
        }
        messages.add(message);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ChatHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view;
        if (viewType == Message.MINE){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_msg_mine, parent, false);

        }
        else if (viewType == Message.OTHER){
           view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_other, parent, false);

        }
        else if (viewType == Message.IMG_MINE){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_img_mine, parent, false);
        }
        else {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_img_other, parent, false);
        }

        return new ChatHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ChatHolder holder, int position) {
        Message message = messages.get(position);
        if (message.getType() == Message.MINE){
            holder.tvMsg.setText(message.getMsg());
        }
        else if (message.getType() == Message.OTHER){
            holder.tvMsg.setText(message.getMsg());
        }
        else if (message.getType() == Message.IMG_MINE){
            holder.img.setImageResource(message.getImg());
        }
        else {
            holder.img.setImageResource(message.getImg());
        }
    }

    @Override
    public int getItemViewType(int position){

        return messages.get(position).getType();
    }

    @Override
    public int getItemCount() {
        return messages == null ? 0 : messages.size();
    }

    class ChatHolder extends RecyclerView.ViewHolder {

        TextView tvMsg;
        ImageView img;
        public ChatHolder(@NonNull View itemView) {
            super(itemView);
            tvMsg = itemView.findViewById(R.id.tv_msg);
            img = itemView.findViewById(R.id.img);
        }
    }
}
